package cn.vcjf.weapp.api.payment.qfwxpay.service.QfApi;

import cn.vcjf.weapp.api.payment.qfwxpay.model.VcQfPayReq;
import cn.vcjf.weapp.api.payment.qfwxpay.model.VcQfPayRes;
import cn.vcjf.weapp.api.payment.qfwxpay.service.AbstractQfWxPayAuth;
import cn.vcjf.weapp.common.util.httpUtils.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static cn.vcjf.weapp.api.payment.qfwxpay.service.AbstractQfWxPayAuth.PAY_PAGE_URL;

/**
 * zhengzihang
 */
@Service
public class WechatPayServiceImpl extends WechatPayService {

	private static Logger logger = LogManager.getLogger(WechatPayServiceImpl.class);

		/*code：E85AB5AF2943441D80FB838B6C228640
        key：8A920BE9718C414982EB5950216429C0*/

	public static String PAY_URL = "https://openapi.qfpay.com/trade/v1/payment";

	public static String REDIRECT_TO_WECHATPAY = "https://o2.qfpay.com/q/direct?";

	/**
	 * 支付接口
	 * @param vcQfPayReq
	 * @return
	 */
	@Override
	public VcQfPayRes doPay(VcQfPayReq vcQfPayReq){
		VcQfPayRes res = VcQfPayRes.failedPayResp("请求失败");
		try {
			res = VcQfPayReq.checkQtPayReq(vcQfPayReq);
			if (!res.getCode().equals("10000")) {
				return res;
			}
			SortedMap<String, String> sortedMap=buildPayParams(vcQfPayReq);
			logger.info("钱方下单:请求地址：{"+PAY_URL+"},请求参数：{"+sortedMap.toString()+"}");
			Map<String, String> headerMap = getHeaderMap(sortedMap);
			String result = HttpClientUtils.httpSendPostFrom(PAY_URL, sortedMap, headerMap);
			JSONObject jsonObject=JSONObject.parseObject(result);
			logger.info("钱方下单:返回信息：{}"+jsonObject.toJSONString());

			return getBasePayRes(jsonObject);
		} catch (Exception e) {
			logger.error("钱方支付接口异常.", e);
			VcQfPayRes.failedPayResp("支付下单失败");
		}
		return res;
	}
	/**
	 * @描述:解析返回参数
	 * @作者:JauYang
	 * @时间:2018年1月31日 上午10:13:35
	 */
	public static VcQfPayRes getBasePayRes(JSONObject resultJsonObject) {
		try {
			VcQfPayRes basePayRes = new VcQfPayRes();

			//保存上游返回的所有信息
			//请求下单结果返回码,0000表示下单成功；
			//1143、1145表示交易中，需要继续查询交易结果； 其他返回码表示失败
			basePayRes.setCode(resultJsonObject.getString("respcd"));
			basePayRes.setMsg(resultJsonObject.getString("respmsg"));
			basePayRes.setErrMsg(resultJsonObject.getString("resperr"));
			basePayRes.setPayUrl(resultJsonObject.getString("qrcode"));
			//订单支付金额，单位分
			basePayRes.setTxAmt(resultJsonObject.getString("txamt"));
			//vc订单号
			basePayRes.setOutTraOrderNo(resultJsonObject.getString("out_trade_no"));
			//钱方端订单号
			basePayRes.setOrderSn(resultJsonObject.getString("syssn"));
			//唤起微信支付的参数
			basePayRes.setResParam(resultJsonObject.getString("pay_params"));
			basePayRes.setResult(resultJsonObject.toString());
			return basePayRes;
		} catch (Exception e) {
			return VcQfPayRes.failedPayResp(e.getMessage());
		}
	}
	/**
	 * 转换支付链接：
	 * */
	public static String getPayUrl(VcQfPayReq basePayReq, JSONObject jsonObject) {
		StringBuilder payUrl = new StringBuilder(REDIRECT_TO_WECHATPAY);
		try {
			payUrl.append("mchntnm="+ URLEncoder.encode(basePayReq.getMerchName(),"utf-8")).
			append("&txamt="+new BigDecimal(basePayReq.getTxamt()).multiply(new BigDecimal(100)).setScale(0).toString()).
			append("&goods_name="+ URLEncoder.encode(basePayReq.getGoodsName()+"付款","utf-8")).
			append("&redirect_url="+URLEncoder.encode(PAY_PAGE_URL,"utf-8")).
			append("&package="+jsonObject.getString("package")).
			append("&timeStamp="+jsonObject.getString("timeStamp")).
			append("&signType="+jsonObject.getString("signType")).
			append("&paySign="+jsonObject.getString("paySign")).
			append("&appId="+jsonObject.getString("appId")).
			append("&nonceStr="+jsonObject.getString("nonceStr"));
		}catch (Exception e){
			e.printStackTrace();
		}
		return payUrl.toString();
	}


	public void getPayRequestEntity(VcQfPayReq req) {
      /*  支付类型
        支付宝扫码:800101；支付宝反扫:800108； 支付宝服务窗：800107；
        微信扫码:800201；微信刷卡:800208； 微信公众号:800207；*/
	}
	/**
	 * @描述:构建钱方支付参数
	 * @作者:JauYang
	 * @时间:2018年1月31日 上午10:13:35
	 */
	public SortedMap<String,String> buildPayParams(VcQfPayReq req) throws IllegalArgumentException {
		SortedMap<String, String> sortedMap = new TreeMap<>();
		sortedMap.put("txamt",new BigDecimal(req.getTxamt()).multiply(new BigDecimal(100)).setScale(0).toString());
		sortedMap.put("txcurrcd", req.getTxcurrcd());
		sortedMap.put("pay_type",req.getPayType());
		sortedMap.put("mchid", req.getMchid());
		sortedMap.put("out_trade_no", req.getOutTradeNo());
		sortedMap.put("txdtm", req.getTxdtm());
		//微信公众号支付:800207
		if(req.getPayType().equals("800207")){
			sortedMap.put("sub_openid", req.getSubOpenid());
		}
		//微信小程序支付:800213
		if(req.getPayType().equals("800213")){
			sortedMap.put("openid", req.getSubOpenid());
		}
		sortedMap.put("goods_name", req.getGoodsName());
		SortedMap<String, String> params = HttpClientUtils.paraFilter(sortedMap);
		String sign = HttpClientUtils.getSign(params, AbstractQfWxPayAuth.KEY);
		sortedMap.put("sign", sign);
		return sortedMap;
	}

	/**
	 * @描述：
	 * @作者：Hongcq
	 * @时间：2018年1月24日 | 下午2:41:44
	 */
	private Map<String, String> getHeaderMap(SortedMap<String, String> sortedMap ){
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("X-QF-SIGN", sortedMap.get("sign"));
		headerMap.put("X-QF-APPCODE", AbstractQfWxPayAuth.APP_CODE);
		sortedMap.remove("sign");
		return headerMap;
	}
}
